package com.easpeed.comon.widget

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log;
import com.bigyu.utils.Logger
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.core.view.forEach
import com.easpeed.comon.bean.PhotoBean
import com.easpeed.comon.utils.ImageUtils
import com.easpeed.comon.utils.setViewIsShow
import com.easpeed.elevator.R
import com.google.android.flexbox.FlexboxLayout
import java.util.UUID

class PhotoSelectView : RelativeLayout {


    //最大数量
    private var maxCount = 9

    //每一行最大数量
    private var maxCountColumn = 4

    private var flexboxLayout: FlexboxLayout? = null

    private val imageCaCheList = ArrayList<PhotoBean>()

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        init()
    }


    private fun initImageList() {
        imageCaCheList.clear()
        imageCaCheList.add(PhotoBean().apply {
            isDefault = true
        })
    }

    private fun init() {
        setWillNotDraw(false)
        minimumHeight = 1

        initImageList()
        val view = LayoutInflater.from(context).inflate(R.layout.item_photo_select_view, null)
        view.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        addView(view)
        flexboxLayout = findViewById(R.id.flex_layout)

    }

    companion object {
        val TYPE_NEW_PHOTO = 1001
        val TYPE_DELETE_PHOTO = 1002
        val TYPE_CLICK_PHOTO = 1003
    }


    private var result: ((PhotoBean?, Int , ImageView) -> Unit)? = null

    /**
     * 图片操作的监听
     */
    fun setImageClickListener(result: ((PhotoBean?, Int  , ImageView) -> Unit)? = null) {
        this.result = result
    }

    private var isAdded = false
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        calculatePhotoSize()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (!isAdded) {
            isAdded = true
            imageCaCheList.forEach {
                flexboxLayout?.addView(addPhoto(it))
            }
            invalidate()
        }
    }

    private var oneWidth: Int = 0

    private fun calculatePhotoSize() {
        if (oneWidth == 0) {
            oneWidth = measuredWidth / maxCountColumn
        }
    }


    /**
     * 支持的最大图片
     */
    fun setMaxCount(maxCount: Int) {
        this.maxCount = maxCount
    }

    fun deletePhoto(bean: PhotoBean) {
        Logger.e("TAG", "deletePhoto: ${bean.toString()}")
        Logger.e("TAG", "deletePhoto: ${imageCaCheList.toString()}")
        flexboxLayout?.childCount?.let {


        }

        Logger.e("TAG", "deletePhoto: ${flexboxLayout?.childCount.toString()}")
        val indexOf = imageCaCheList.indexOf(bean)
        flexboxLayout?.removeView(flexboxLayout?.findViewWithTag<View>(bean.id))
        if (indexOf != -1) {
            imageCaCheList.removeAt(indexOf)
            if (!imageCaCheList.last().isDefault) {
                addNewPhoto(isDefault = true)
            }
            invalidate()
            postInvalidate()
        }
    }

    fun getAllImage(): ArrayList<PhotoBean> {
        val list = ArrayList<PhotoBean>()
        list.addAll(imageCaCheList)
        if (list.lastOrNull()?.isDefault == true) {
            list.removeLastOrNull()
        }
        return list
    }

    fun addNewPhoto(isDefault: Boolean = false, imageUrl: String? = null, bitmap: Bitmap? = null) {
        val count = imageCaCheList.count()
        var isCanAdd = false


        var isLastDefault = false
        if (imageCaCheList.lastOrNull()?.isDefault == true) {
            isLastDefault = true
        }


        var index = -1
        if (count >= maxCount) {
            //如果最后一张是添加的样式则删除最后一张
            if (isLastDefault) {
                imageCaCheList.removeLastOrNull()
                flexboxLayout?.removeViewAt(count - 1)
                isCanAdd = true
                index = -1
            }
        } else {
            if (isLastDefault) {
                index = imageCaCheList.count() - 1
            } else {
                index = imageCaCheList.count()
            }
            isCanAdd = true
        }
        if (isCanAdd) {
            val bean = PhotoBean()
//            bean.id = UUID.randomUUID().toString()
            bean.isDefault = isDefault
            bean.imageUrl = imageUrl
            bean.bitmap = bitmap

            if (index == -1) {
                imageCaCheList.add(bean)
                flexboxLayout?.addView(addPhoto(bean))
            } else {
                imageCaCheList.add(index, bean)
                flexboxLayout?.addView(addPhoto(bean), index)
            }
            Logger.e("TAG", "addNewPhoto: ${imageCaCheList.toString()}")
        }
    }

    /**
     * 渲染图片
     */
    private fun addPhoto(photoBean: PhotoBean): View {
        val frame = LayoutInflater.from(context).inflate(R.layout.item_photo_view, null)
        val params = FlexboxLayout.LayoutParams(oneWidth, oneWidth)
        params.flexBasisPercent = (oneWidth * 1f / measuredWidth)
        frame.layoutParams = params
        frame.tag = photoBean.id
        val deleteView = frame.findViewById<View>(R.id.delete)
        val imageView = frame.findViewById<ImageView>(R.id.image)
        val isDefault = photoBean.isDefault
        //是否显示删除符号
        deleteView?.setViewIsShow(!isDefault)

        if (!isDefault) {
            if (!TextUtils.isEmpty(photoBean.imageUrl)) {
                ImageUtils.loadImage(photoBean.imageUrl, R.mipmap.ww_icon_default_loading_photo, R.mipmap.ww_icon_default_error_photo, imageView)
            } else if (photoBean.bitmap != null) {
                imageView.setImageBitmap(photoBean.bitmap)
            } else {
                imageView.setImageResource(R.mipmap.ww_icon_default_add_photo)
            }
        }

        imageView?.setOnClickListener {
            if (isDefault) {
                result?.invoke(photoBean, TYPE_NEW_PHOTO , imageView)
            } else {
                result?.invoke(photoBean, TYPE_CLICK_PHOTO,imageView)
            }
        }

        deleteView?.setOnClickListener {
            result?.invoke(photoBean, TYPE_DELETE_PHOTO,imageView)
        }

        return frame
    }

}